package com.ljdemo.lrecorder.crash

import android.content.Context
import android.os.Looper
import android.util.Log

/**
 * 防止应用崩溃跳出
 * <br/>
 * 来自网易云课堂
 * <br/>
 * 创建日期 : 2023/3/14
 * */
class CrashProjectManager private constructor(){

    companion object {
        private var mInstance: CrashProjectManager? = null
        private var mContext: Context? = null
        fun getInstance(context: Context): CrashProjectManager? {
            if (mInstance == null) {
                mContext = context.applicationContext
                mInstance = CrashProjectManager()
            }
            return mInstance
        }
    }

    fun init() {
        //crach防护
        Thread.setDefaultUncaughtExceptionHandler { t, e ->
            Log.e("uncaughtException", "应用发生崩溃")
            if (t === Looper.getMainLooper().thread) {
                handleMainThread(e)
            }
        }
    }

    private fun handleMainThread(e:Throwable){
        while (true){
            try {
                Looper.loop()
            }catch (e:Throwable){
                Log.e("handleMainThread","应用发生崩溃")
            }
        }
    }

}